package com.ncmmall.component.schedule.bootstrap.spring;

import com.ncmmall.component.schedule.bootstrap.Bootstrap;
import com.ncmmall.component.schedule.bootstrap.LogoAscil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.concurrent.CountDownLatch;

/**
 *
 */
public class SpringBootstrap implements Bootstrap {

    private static final Logger LOG = LoggerFactory.getLogger(SpringBootstrap.class);

    private final String[] configLocations;
    private ClassPathXmlApplicationContext applicationContext;

    public SpringBootstrap(String... configLocations) {
        this.configLocations = configLocations;
    }

    @Override
    public void bootstrap() {

        new LogoAscil().imageToASCII();

        LOG.warn("start boostrap...");

        start();

        final CountDownLatch signal = new CountDownLatch(1);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                signal.countDown();
                SpringBootstrap.this.stop();
            }
        });

        new Thread() {
            @Override
            public void run() {
                try {
                    signal.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    LOG.error(e.getMessage(), e);
                }
            }
        }.start();

        LOG.warn("start bootstrap finished.");

    }

    private void start() {
        applicationContext = new ClassPathXmlApplicationContext(configLocations);
        applicationContext.start();
    }

    private void stop() {
        applicationContext.stop();
        applicationContext.close();
    }
}
